Script entrypoints

Write Global Scripts in python

Created: June 23rd 2019
Updated: December 7th 2019
Connect with us on
image
image

Script entrypoints are useful for allowing you to write scripts that can be accessed anywhere on the machine. They are setup in the setup.py file of your python package.

Usage In this repo you can see the demo code and actually run it using the steps below

  1. Install as a pip package using pip install .
  2. In your terminal type command_name (literally command_name, this is not a placeholder)
  3. The help text for the command will appear, and this can be run in any folder on your computer

Note that to uninstall the script you need to type pip uninstall entrypoint-demo

Real World Example Lets say you are writing a utility to download a youtube video, you want this to be callable from anywhere in the OS by typing $ yt-downloader --url="<video URL>"

To do this you would have a line in your setup.py file to specify

setuptools.setup(
    # Some setup info
    entry_points={
          'console_scripts': ['yt-downloader = package.youtube:downloader']
      },
    # More setup info

This can be seen in full detail with the PyTube module

Files

File Tree

This is the organization for the files below

(root is the top level directory)

root/
├─ setup.py
└─ package/
   ├─ command_line_utility_demo.py
   └─ __init__.py

setup.py

import setuptools
def get_content(filename):
    """ Gets the content of a file and returns it as a string

    Args:
    filename(str): Name of file to pull content from

    Returns:
    str: Content from file
    """
    with open(filename, "r") as full_description:
        content = full_description.read()
    return content
setuptools.setup(
    name="entrypoint demo",
    version="0.0.1",
    author="Kieran Wood",
    author_email="[email protected]",
    description="A demo for script entrypoints",
    long_description=get_content("readme.md"),
    long_description_content_type="text/markdown",
    url=r"https://github.com/canadian-coding/posts/2019/June/June%2023rd%20-%20Python%20Entrypoints",
    packages=setuptools.find_packages(),
    entry_points={
    'console_scripts': ['command_name = package.command_line_utility:main']
    },
    classifiers=[
    "Programming Language :: Python :: 3",
    "Operating System :: OS Independent",
    ],
)

/package/command_line_utility_demo.py

"""
Description:
    An example command line utility intended to be useable in any part of the OS. Once installed\
    You should be able to run the $ <command_name> the same way as you would run $ command_line_utility.py
Example:
    $ command_name -h
"""
import argparse # Used to create an argument parser
import sys # Used to check if any arguments have been provided
def main():
    """The main function where everything lives, you need a function to point the entrypoint to so it can\
    be run.
    """
    # Setting up Main Argument Parser
    main_parser = argparse.ArgumentParser(description="A demo of python entrypoint")
    main_parser.add_argument("-v",'--version', action='version', version='command_name V0.0.1')
    # Setting up the main subparser
    subparsers = main_parser.add_subparsers(help="This is the help command, it is called by using -h or --help")
    example_command = subparsers.add_parser('example_command', help='An example with some help text')
    # Print help if no argument is provided
    if len(sys.argv)==1:
        main_parser.print_help()
        args = main_parser.parse_args()

/package/__init__.py

This file is empty and just used to mark the folder package as a module

Thank you for your support!

Be sure to share the post if it was helpful!